package com.mti.controller;


import com.alibaba.fastjson.JSON;
import com.mti.component.ResponseCallBack;
import com.mti.component.ResponseCriteria;
import com.mti.component.ResponseInfo;
import com.mti.component.redis.CacheKeyEnum;
import com.mti.component.redis.RedisService;
import com.mti.dao.model.LfCodeDeviceEntity;
import com.mti.service.ILfCodeDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yangsp
 * @since 2019-04-29
 */
@Api(value="电子围栏数据接口",description="电子围栏数据接口")
@RestController
@RequestMapping("/lf/codedevice")
@Slf4j
public class LfCodeDeviceController {

    @Autowired
    private ILfCodeDeviceService service;

    @Autowired
    private RedisService redisService;

    @ApiOperation(value="通过id查询记录",notes="通过id查询记录")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Mono<ResponseInfo> getById(@PathVariable("id") String id) {
        return Mono.just(new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                LfCodeDeviceEntity entity = service.getById(id);
                criteria.addSingleResult(entity);
            }
        }.sendRequest());
    }

    @ApiOperation(value="查询列表记录",notes="查询列表记录")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Mono<ResponseInfo> selectAll() {
        return Mono.just(new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                List<LfCodeDeviceEntity> entitys = new ArrayList<LfCodeDeviceEntity>();
                boolean hasCache = redisService.has(CacheKeyEnum.RedisPrefixKeys.R_code_device.getKey());
                if(hasCache){
                    Object entitysJson = redisService.getValue(CacheKeyEnum.RedisPrefixKeys.R_code_device.getKey());
                    entitys = JSON.parseArray(entitysJson.toString(), LfCodeDeviceEntity.class);
                    System.out.println("ILfCodeDeviceService entitys==>" + entitys.size());
                }else{
                    entitys = service.list();
                    System.out.println("ILfCodeDeviceService entitys==>" + entitys.size());
                    redisService.setValue(CacheKeyEnum.RedisPrefixKeys.R_code_device.getKey(), JSON.toJSONString(entitys), 86400000);
                }
                criteria.addSingleResult(entitys);
            }
        }.sendRequest());
    }

}
